﻿using System.Drawing;

namespace HtmlTextsLength.Sources.OriginText;

public class FontResource
{
    private double HtmlSize => 19.9;//a

    private double HtmlFontSize => 36;
    // C# map
    public FontResource()
    {
        Maps[' '] = 16 * 20.49 / 19.9;
    }

    public Dictionary<char, double>? Maps { get; set; } = new()
    {
        {
          ' ', 16 * 20.49 / 19.9d
        },
    };

    public double GetWidthOfString(string text, double fs)
    {
        return text.Sum(c => GetWidthOfChar(c, fs));
    }

    private double GetWidthOfChar(char str, double fs)
    {
        if (Maps == null) throw new Exception("未初始化");
        if (Maps.TryGetValue(str, out var map))
        {
            return map / 20.49609375 * HtmlSize / HtmlFontSize * fs*582/317.646;
        }

        var width = GetSizeOfChar(str);
        Maps[str] = width;
        return width / 20.49609375 * HtmlSize / HtmlFontSize * fs*582/317.646;
    }

    private double GetSizeOfChar(char str, double fs=36)
    {
        return InnerCountSize(new string(str,2), fs) - InnerCountSize(new string(str,1), fs);
    }
    private double InnerCountSize(string text,double fs)
    {
        var font = new Font("Microsoft YaHei", (float)fs, FontStyle.Regular, GraphicsUnit.Pixel);

        using var graphics = Graphics.FromImage(new Bitmap(1, 1));
        var size = graphics.MeasureString(text, font);
        var width = size.Width;
        return width;
    }
}